#include "devicesearchwidget.h"
#include "ui_devicesearchwidget.h"
#include <QMessageBox>
#include <QFileDialog>
#include <QTextStream>
#include <QJsonArray>
#include <QDebug>
#include <QDesktopServices>
#include <QUrl>
#include <QHeaderView>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLineEdit>
#include <QPushButton>
#include <QFont>
#include <QFormLayout>
#include <QDialogButtonBox>
#include <QComboBox>
#include <QLabel>
#include <QGroupBox>

// LoginDialog Implementation
LoginDialog::LoginDialog(const QString &deviceAddress, QWidget *parent)
    : QDialog(parent)
{
    setWindowTitle(QString("Login to Device - %1").arg(deviceAddress));
    setModal(true);
    resize(300, 150);
    
    QFormLayout *formLayout = new QFormLayout();
    
    m_usernameEdit = new QLineEdit();
    m_usernameEdit->setText("admin");  // 默认用户名
    m_passwordEdit = new QLineEdit();
    m_passwordEdit->setEchoMode(QLineEdit::Password);
    m_rememberMeCheckBox = new QCheckBox("Remember credentials");
    
    formLayout->addRow("Username:", m_usernameEdit);
    formLayout->addRow("Password:", m_passwordEdit);
    formLayout->addRow("", m_rememberMeCheckBox);
    
    QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
    connect(buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept);
    connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);
    
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->addLayout(formLayout);
    mainLayout->addWidget(buttonBox);
    
    m_usernameEdit->setFocus();
}

QString LoginDialog::getUsername() const
{
    return m_usernameEdit->text().trimmed();
}

QString LoginDialog::getPassword() const
{
    return m_passwordEdit->text();
}

bool LoginDialog::getRememberMe() const
{
    return m_rememberMeCheckBox->isChecked();
}

// NetworkConfigDialog Implementation
NetworkConfigDialog::NetworkConfigDialog(QWidget *parent)
    : QDialog(parent)
{
    setWindowTitle("网络配置");
    setModal(true);
    resize(500, 400);
    
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    
    // 创建状态标签
    m_statusLabel = new QLabel("点击'获取配置'以加载当前网络配置");
    m_statusLabel->setStyleSheet("QLabel { color: blue; }");
    mainLayout->addWidget(m_statusLabel);
    
    // 创建获取配置按钮
    m_getConfigBtn = new QPushButton("获取配置");
    connect(m_getConfigBtn, &QPushButton::clicked, this, &NetworkConfigDialog::onGetConfigClicked);
    mainLayout->addWidget(m_getConfigBtn);
    
    // 创建配置表单
    QGroupBox *configGroup = new QGroupBox("网络配置");
    QFormLayout *formLayout = new QFormLayout(configGroup);
    
    // 网络接口选择
    m_interfaceCombo = new QComboBox();
    m_interfaceCombo->addItem("eth0");
    m_interfaceCombo->addItem("wlan0");
    formLayout->addRow("网络接口:", m_interfaceCombo);
    
    // 启用网卡
    m_enableCheckBox = new QCheckBox();
    m_enableCheckBox->setChecked(true);
    formLayout->addRow("启用网卡:", m_enableCheckBox);
    
    // 网络模式
    m_modeCombo = new QComboBox();
    m_modeCombo->addItem("DHCP", "dhcp");
    m_modeCombo->addItem("静态IP", "static");
    connect(m_modeCombo, QOverload<int>::of(&QComboBox::currentIndexChanged), 
            this, &NetworkConfigDialog::onModeChanged);
    formLayout->addRow("网络模式:", m_modeCombo);
    
    // 静态IP配置组
    m_staticConfigWidget = new QWidget();
    QFormLayout *staticLayout = new QFormLayout(m_staticConfigWidget);
    staticLayout->setContentsMargins(0, 0, 0, 0);
    
    m_ipAddressEdit = new QLineEdit();
    m_ipAddressEdit->setPlaceholderText("例如: 192.168.1.100");
    staticLayout->addRow("IP地址:", m_ipAddressEdit);
    
    m_netmaskEdit = new QLineEdit();
    m_netmaskEdit->setPlaceholderText("例如: 255.255.255.0");
    staticLayout->addRow("子网掩码:", m_netmaskEdit);
    
    m_gatewayEdit = new QLineEdit();
    m_gatewayEdit->setPlaceholderText("例如: 192.168.1.1");
    staticLayout->addRow("网关:", m_gatewayEdit);
    
    formLayout->addRow(m_staticConfigWidget);
    
    mainLayout->addWidget(configGroup);
    
    // 按钮
    QHBoxLayout *buttonLayout = new QHBoxLayout();
    m_setConfigBtn = new QPushButton("设置配置");
    connect(m_setConfigBtn, &QPushButton::clicked, this, &NetworkConfigDialog::onSetConfigClicked);
    
    QPushButton *closeBtn = new QPushButton("关闭");
    connect(closeBtn, &QPushButton::clicked, this, &QDialog::close);
    
    buttonLayout->addWidget(m_setConfigBtn);
    buttonLayout->addStretch();
    buttonLayout->addWidget(closeBtn);
    mainLayout->addLayout(buttonLayout);
    
    // 初始状态
    onModeChanged();
}

void NetworkConfigDialog::setNetworkConfig(const QJsonObject &config)
{
    m_statusLabel->setText("网络配置已加载");
    m_statusLabel->setStyleSheet("QLabel { color: green; }");
    
    // 解析配置
    if (config.contains("default_interface")) {
        QString defaultInterface = config["default_interface"].toString();
        int index = m_interfaceCombo->findText(defaultInterface);
        if (index >= 0) {
            m_interfaceCombo->setCurrentIndex(index);
        }
    }
    
    if (config.contains("interfaces")) {
        QJsonObject interfaces = config["interfaces"].toObject();
        
        // 查找第一个接口或默认接口
        QString interfaceName = config.contains("default_interface") ? 
                               config["default_interface"].toString() : 
                               interfaces.keys().first();
        
        if (interfaces.contains(interfaceName)) {
            QJsonObject interfaceConfig = interfaces[interfaceName].toObject();
            
            // 设置启用状态
            if (interfaceConfig.contains("enable")) {
                m_enableCheckBox->setChecked(interfaceConfig["enable"].toBool());
            }
            
            // 设置网络模式
            if (interfaceConfig.contains("mode")) {
                QString mode = interfaceConfig["mode"].toString();
                int index = m_modeCombo->findData(mode);
                if (index >= 0) {
                    m_modeCombo->setCurrentIndex(index);
                }
            }
            
            // 设置静态IP配置
            if (interfaceConfig.contains("ipv4")) {
                QJsonObject ipv4 = interfaceConfig["ipv4"].toObject();
                if (ipv4.contains("address")) {
                    m_ipAddressEdit->setText(ipv4["address"].toString());
                }
                if (ipv4.contains("netmask")) {
                    m_netmaskEdit->setText(ipv4["netmask"].toString());
                }
                if (ipv4.contains("gateway")) {
                    m_gatewayEdit->setText(ipv4["gateway"].toString());
                }
            }
        }
    }
    
    onModeChanged(); // 更新界面状态
}

void NetworkConfigDialog::onModeChanged()
{
    QString mode = m_modeCombo->currentData().toString();
    m_staticConfigWidget->setVisible(mode == "static");
}

void NetworkConfigDialog::onGetConfigClicked()
{
    m_statusLabel->setText("正在获取网络配置...");
    m_statusLabel->setStyleSheet("QLabel { color: blue; }");
    emit networkConfigRequested();
}

void NetworkConfigDialog::onSetConfigClicked()
{
    QString interfaceName = m_interfaceCombo->currentText();
    bool enable = m_enableCheckBox->isChecked();
    QString mode = m_modeCombo->currentData().toString();
    
    QString ipAddress, netmask, gateway;
    if (mode == "static") {
        ipAddress = m_ipAddressEdit->text().trimmed();
        netmask = m_netmaskEdit->text().trimmed();
        gateway = m_gatewayEdit->text().trimmed();
        
        if (ipAddress.isEmpty() || netmask.isEmpty() || gateway.isEmpty()) {
            m_statusLabel->setText("错误: 静态IP模式下，IP地址、子网掩码和网关都不能为空");
            m_statusLabel->setStyleSheet("QLabel { color: red; }");
            return;
        }
    }
    
    m_statusLabel->setText("正在设置网络配置...");
    m_statusLabel->setStyleSheet("QLabel { color: blue; }");
    
    emit setNetworkConfigRequested(interfaceName, enable, mode, ipAddress, netmask, gateway);
}

// DeviceSearchWidget Implementation
DeviceSearchWidget::DeviceSearchWidget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::DeviceSearchWidget)
    , m_deviceManager(new DeviceManager(this))
    , m_discoveryClient(&Discovery::DiscoveryClient::instance())
    , m_discoveryCallbackHandle(-1)
    , m_networkConfigDialog(nullptr)
    , m_firmwareUpgradeDialog(nullptr)
{
    ui->setupUi(this);
    setupUI();

    // 初始化进度定时器（用于按时间更新进度条）
    m_progressTimer = new QTimer(this);
    m_progressTimer->setInterval(200); // 200ms 更新一次，足够平滑
    connect(m_progressTimer, &QTimer::timeout, [this]() {
        if (m_searchTimeoutSeconds <= 0) {
            ui->progressBar->setValue(0);
            return;
        }

        qint64 elapsedMs = m_searchElapsedTimer.elapsed();
        double elapsedSec = elapsedMs / 1000.0;
        double ratio = elapsedSec / static_cast<double>(m_searchTimeoutSeconds);
        int value = static_cast<int>(qBound(0.0, ratio, 1.0) * 100.0);
        ui->progressBar->setValue(value);
    });
    
    // 初始化设备ID（使用MAC地址或者UUID）
    m_deviceId = QUuid::createUuid().toString(QUuid::WithoutBraces);
    
    // Connect discovery client signals
    connect(m_discoveryClient, &Discovery::DiscoveryClient::deviceFound, 
            this, &DeviceSearchWidget::onDiscoveryDeviceFound);
    connect(m_discoveryClient, &Discovery::DiscoveryClient::discoveryFinished, 
            this, &DeviceSearchWidget::onDiscoveryFinished);
    connect(m_discoveryClient, &Discovery::DiscoveryClient::errorOccurred, 
            this, &DeviceSearchWidget::onDiscoveryError);
    
    // Connect device manager signals and slots
    connect(m_deviceManager, &DeviceManager::connectionStateChanged, 
            this, &DeviceSearchWidget::onDeviceConnectionStateChanged);
    connect(m_deviceManager, &DeviceManager::errorOccurred, 
            this, &DeviceSearchWidget::onDeviceError);
    
    // 连接登录相关信号槽
    connect(m_deviceManager, &DeviceManager::challengeReceived, 
            this, &DeviceSearchWidget::onChallengeReceived);
    connect(m_deviceManager, &DeviceManager::loginSuccess, 
            this, &DeviceSearchWidget::onLoginSuccess);
    connect(m_deviceManager, &DeviceManager::loginFailed, 
            this, &DeviceSearchWidget::onLoginFailed);
    
    // 连接网络配置相关信号槽
    connect(m_deviceManager, &DeviceManager::networkConfigReceived,
            this, &DeviceSearchWidget::onNetworkConfigReceived);
    connect(m_deviceManager, &DeviceManager::networkConfigSetResult,
            this, &DeviceSearchWidget::onNetworkConfigSetResult);
}

DeviceSearchWidget::~DeviceSearchWidget()
{
    if (m_discoveryCallbackHandle != -1) {
        m_discoveryClient->unregisterCallback(m_discoveryCallbackHandle);
    }
    delete m_firmwareUpgradeDialog;
    delete ui;
}

void DeviceSearchWidget::setupUI()
{
    ui->tblDevices->horizontalHeader()->setStretchLastSection(true);
    ui->tblDevices->setColumnWidth(0, 120);  // IP Address
    ui->tblDevices->setColumnWidth(1, 60);   // Port
    ui->tblDevices->setColumnWidth(2, 100);  // Device Type
    ui->tblDevices->setColumnWidth(3, 100);  // Manufacturer
    ui->tblDevices->setColumnWidth(4, 120);  // Model
    
    ui->splitter->setStretchFactor(0, 2);
    ui->splitter->setStretchFactor(1, 1);
    
    // 加载网络接口列表
    loadNetworkInterfaces();
    
    updateDeviceCount();
}

void DeviceSearchWidget::on_btnSearch_clicked()
{
    qDebug() << "=== Discovery button clicked ===";
    
    // 如果发现客户端正在运行，停止搜索
    if (m_discoveryClient) {
        qDebug() << "Stopping any existing discovery...";
        m_discoveryClient->stop();
    }
    
    // 清除之前的搜索结果
    m_foundDevices.clear();
    ui->tblDevices->setRowCount(0);
    ui->txtDeviceDetails->clear();
    updateDeviceCount();
    
    // 使用可配置的超时时间（例如 10 秒）
    int timeout = 10;
    
    // 获取选定的网络接口
    QString selectedInterface = getSelectedNetworkInterface();
    
    qDebug() << "Starting multicast device discovery with timeout:" << timeout << "seconds";
    if (selectedInterface.isEmpty()) {
        QMessageBox::warning(this, "提示", "未检测到可用的网络接口，请检查网络连接。");
        setSearchEnabled(true);
        return;
    } else {
        qDebug() << "Using network interface:" << selectedInterface;
    }
    
    setSearchEnabled(false);
    ui->lblProgress->setText("Broadcasting discovery request...");
    ui->progressBar->setValue(0);

    // 启动基于时间的进度更新
    m_searchTimeoutSeconds = timeout;
    m_searchElapsedTimer.restart();
    m_progressTimer->start();
    
    // 启动发现客户端进行组播搜索，传递选定的网络接口
    // 这里可以设置适当的重试次数（例如 2 次：总共发送 3 轮发现请求）
    int retryCount = 2;
    if (!m_discoveryClient->start(timeout, selectedInterface, retryCount)) {
        qWarning() << "Failed to start discovery client";
        ui->lblProgress->setText("Failed to start discovery client");
        setSearchEnabled(true);
    } else {
        qDebug() << "Discovery client started successfully";
        ui->lblProgress->setText(QString("Broadcasting on %1, waiting for responses...").arg(selectedInterface));
    }
}

void DeviceSearchWidget::on_btnStop_clicked()
{
    qDebug() << "=== Stop button clicked ===";
    
    // 停止发现客户端
    if (m_discoveryClient) {
        m_discoveryClient->stop();
    }
    
    setSearchEnabled(true);
    ui->lblProgress->setText("Discovery stopped.");
    // 停止进度更新并保持当前值，或重置为 0
    if (m_progressTimer) {
        m_progressTimer->stop();
    }
}

void DeviceSearchWidget::on_btnRefresh_clicked()
{
    on_btnSearch_clicked();
}

void DeviceSearchWidget::on_btnExport_clicked()
{
    if (m_foundDevices.isEmpty()) {
        QMessageBox::information(this, "Information", "No devices to export.");
        return;
    }
    
    QString fileName = QFileDialog::getSaveFileName(this, "Export Device List", 
                                                   "device_list.csv", 
                                                   "CSV Files (*.csv)");
    if (fileName.isEmpty()) return;
    
    QFile file(fileName);
    if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        QTextStream out(&file);
        out << "IP Address,Port,Device Type,Manufacturer,Model,Status,Web Interface\n";
        
        for (const DeviceInfo &device : m_foundDevices) {
            out << device.ipAddress << "," 
                << device.port << ","
                << device.deviceType << ","
                << device.manufacturer << ","
                << device.model << ","
                << device.status << ","
                << device.webInterface << "\n";
        }
        
        QMessageBox::information(this, "Success", "Device list exported successfully.");
    }
}

void DeviceSearchWidget::on_btnConnect_clicked()
{
    int row = ui->tblDevices->currentRow();
    if (row < 0 || row >= m_foundDevices.size()) return;
    
    const DeviceInfo &device = m_foundDevices[row];
    
    // 确保设备已添加到设备管理器中
    if (!m_deviceManager->hasDevice(device.ipAddress)) {
        m_deviceManager->addDevice(device.ipAddress, m_deviceId);
    }
    
    if (m_deviceManager->isConnected(device.ipAddress)) {
        // 如果已连接，则断开连接
        m_deviceManager->disconnectFromDevice(device.ipAddress);
        return;
    }
    
    // 连接到设备并进行登录
    connectToDeviceWithLogin(device);
}

void DeviceSearchWidget::on_btnViewStream_clicked()
{
    int row = ui->tblDevices->currentRow();
    if (row < 0 || row >= m_foundDevices.size()) return;
    
    const DeviceInfo &device = m_foundDevices[row];
    
    if (device.ipAddress.isEmpty()) {
        QMessageBox::warning(this, "Warning", "No device IP address available.");
        return;
    }
    
    // 生成默认的RTSP URL (通道1，主码流)
    QString rtspUrl = device.getMainStreamUrl(1);
    
    // 创建一个新的视频播放窗口
    QWidget *videoWindow = new QWidget();
    videoWindow->setWindowTitle(QString("Video Stream - %1 (%2)")
                               .arg(device.manufacturer)
                               .arg(device.ipAddress));
    videoWindow->setMinimumSize(800, 600);
    videoWindow->setAttribute(Qt::WA_DeleteOnClose); // 关闭时自动删除
    
    // 创建布局
    QVBoxLayout *layout = new QVBoxLayout(videoWindow);
    layout->setContentsMargins(5, 5, 5, 5);
    
    // 创建控制按钮布局
    QHBoxLayout *controlLayout = new QHBoxLayout();
    
    // 添加RTSP URL显示和编辑
    QLabel *urlLabel = new QLabel("RTSP URL:");
    QLineEdit *urlEdit = new QLineEdit(rtspUrl);
    urlEdit->setFont(QFont("Consolas", 9));
    
    // 添加控制按钮
    QPushButton *playBtn = new QPushButton("Play");
    QPushButton *pauseBtn = new QPushButton("Pause");
    QPushButton *stopBtn = new QPushButton("Stop");
    
    controlLayout->addWidget(urlLabel);
    controlLayout->addWidget(urlEdit, 1);
    controlLayout->addWidget(playBtn);
    controlLayout->addWidget(pauseBtn);
    controlLayout->addWidget(stopBtn);
    
    // 创建FFmpeg视频播放widget
    FFmpegWidget *videoWidget = new FFmpegWidget(videoWindow);
    videoWidget->setMinimumSize(640, 480);
    videoWidget->setStyleSheet("background-color: black; border: 1px solid gray;");
    
    // 添加到布局
    layout->addLayout(controlLayout);
    layout->addWidget(videoWidget, 1);
    
    // 连接按钮信号
    connect(playBtn, &QPushButton::clicked, [videoWidget, urlEdit]() {
        QString url = urlEdit->text().trimmed();
        if (!url.isEmpty()) {
            qDebug() << "Playing RTSP stream:" << url;
            videoWidget->setUrl(url);
            videoWidget->open();
        }
    });
    
    connect(pauseBtn, &QPushButton::clicked, [videoWidget]() {
        qDebug() << "Pausing video stream";
        videoWidget->pause();
    });
    
    connect(stopBtn, &QPushButton::clicked, [videoWidget]() {
        qDebug() << "Stopping video stream";
        videoWidget->close();
    });
    
    // 显示窗口
    videoWindow->show();
    
    // 自动开始播放
    qDebug() << "Auto-starting RTSP stream:" << rtspUrl;
    videoWidget->setUrl(rtspUrl);
    videoWidget->open();
}

void DeviceSearchWidget::on_btnWebInterface_clicked()
{
    int row = ui->tblDevices->currentRow();
    if (row < 0 || row >= m_foundDevices.size()) return;
    
    const DeviceInfo &device = m_foundDevices[row];
    
    if (!device.webInterface.isEmpty()) {
        QDesktopServices::openUrl(QUrl(device.webInterface));
    }
}

void DeviceSearchWidget::on_btnModifyParams_clicked()
{
    int row = ui->tblDevices->currentRow();
    if (row < 0 || row >= m_foundDevices.size()) return;
    
    const DeviceInfo &device = m_foundDevices[row];
    
    // 检查是否已登录
    Device *deviceObj = m_deviceManager->getDevice(device.ipAddress);
    if (!deviceObj || !deviceObj->isLoggedIn() || !deviceObj->isConnected()) {
        QMessageBox::warning(this, "警告", "请先连接并登录到设备");
        return;
    }
    
    // 创建网络配置对话框（如果不存在）
    if (!m_networkConfigDialog) {
        m_networkConfigDialog = new NetworkConfigDialog(this);
        
        // 连接对话框信号
        connect(m_networkConfigDialog, &NetworkConfigDialog::networkConfigRequested,
                [this, device]() {
                    m_deviceManager->getNetworkConfig(device.ipAddress);
                });
        
        connect(m_networkConfigDialog, &NetworkConfigDialog::setNetworkConfigRequested,
                [this, device](const QString &interfaceName, bool enable, const QString &mode,
                       const QString &ipAddress, const QString &netmask, const QString &gateway) {
                    m_deviceManager->setNetworkConfig(device.ipAddress, interfaceName, enable, mode, ipAddress, netmask, gateway);
                });
    }
    
    // 显示对话框
    m_networkConfigDialog->show();
    m_networkConfigDialog->raise();
    m_networkConfigDialog->activateWindow();
}

void DeviceSearchWidget::on_btnUpgrade_clicked()
{
    int row = ui->tblDevices->currentRow();
    if (row < 0 || row >= m_foundDevices.size()) return;
    
    const DeviceInfo &device = m_foundDevices[row];
    
    // 检查设备是否已连接并登录
    Device *deviceObj = m_deviceManager->getDevice(device.ipAddress);
    if (!deviceObj || !deviceObj->isLoggedIn() || !deviceObj->isConnected()) {
        QMessageBox::warning(this, tr("Warning"), tr("Please connect and login to the device first."));
        return;
    }
    
    // 创建固件升级对话框（如果不存在）
    if (!m_firmwareUpgradeDialog) {
        m_firmwareUpgradeDialog = new FirmwareUpgradeDialog(device.ipAddress, m_deviceManager, this);
    } else {
        // 更新IP地址（如果需要）
        // 注意：在这种实现中，我们为每个设备创建一个新对话框
        delete m_firmwareUpgradeDialog;
        m_firmwareUpgradeDialog = new FirmwareUpgradeDialog(device.ipAddress, m_deviceManager, this);
    }
    
    // 显示对话框
    m_firmwareUpgradeDialog->show();
    m_firmwareUpgradeDialog->raise();
    m_firmwareUpgradeDialog->activateWindow();
}

void DeviceSearchWidget::on_tblDevices_itemSelectionChanged()
{
    int row = ui->tblDevices->currentRow();
    bool hasSelection = row >= 0 && row < m_foundDevices.size();
    
    ui->btnConnect->setEnabled(hasSelection);
    ui->btnViewStream->setEnabled(hasSelection);
    ui->btnWebInterface->setEnabled(hasSelection);
    ui->btnModifyParams->setEnabled(hasSelection);
    ui->btnUpgrade->setEnabled(hasSelection);
    
    if (hasSelection) {
        updateDeviceDetails(m_foundDevices[row]);
    } else {
        ui->txtDeviceDetails->setHtml("<b>Select a device from the list to view details...</b>");
    }
}

void DeviceSearchWidget::onDeviceFound(const DeviceInfo &device)
{
    qDebug() << "=== DeviceSearchWidget::onDeviceFound called ===";
    qDebug() << "Adding device to list and table...";
    
    m_foundDevices.append(device);
    addDeviceToTable(device);
    updateDeviceCount();
    
    qDebug() << "Device added successfully. Total devices:" << m_foundDevices.size();
}

void DeviceSearchWidget::onDiscoveryDeviceFound(const Discovery::DeviceDiscoveryInfo &device)
{
    qDebug() << "=== DeviceSearchWidget::onDiscoveryDeviceFound called ===";
    qDebug() << "Device IP:" << device.ipAddress;
    qDebug() << "Device Type:" << device.deviceType;
    qDebug() << "Manufacturer:" << device.manufacturer;
    qDebug() << "Model:" << device.model;
    
    // 将发现的设备转换为DeviceInfo格式
    DeviceInfo deviceInfo;
    deviceInfo.ipAddress = device.ipAddress;
    deviceInfo.port = device.port;
    deviceInfo.deviceType = device.deviceType;
    deviceInfo.manufacturer = device.manufacturer;
    deviceInfo.model = device.model;
    deviceInfo.status = device.status;
    deviceInfo.webInterface = device.webInterface;
    deviceInfo.rtspUrl = device.rtspUrl;
    deviceInfo.additionalInfo = device.additionalInfo;
    
    qDebug() << "Converting to DeviceInfo and calling onDeviceFound...";
    onDeviceFound(deviceInfo);
}

void DeviceSearchWidget::onDiscoveryFinished()
{
    setSearchEnabled(true);
    if (m_progressTimer) {
        m_progressTimer->stop();
    }
    ui->progressBar->setValue(100);
    ui->lblProgress->setText(QString("Discovery finished. Found %1 devices.").arg(m_foundDevices.size()));
    
    qDebug() << "Discovery finished. Found" << m_foundDevices.size() << "devices.";
}

void DeviceSearchWidget::onDiscoveryError(const QString &error)
{
    ui->lblProgress->setText(QString("Discovery error: %1").arg(error));
    setSearchEnabled(true);
}

void DeviceSearchWidget::setSearchEnabled(bool enabled)
{
    if (ui->btnSearch) {
        ui->btnSearch->setEnabled(enabled);
        if (enabled) {
            ui->btnSearch->setText("Start Discovery");
        } else {
            ui->btnSearch->setText("Discovering...");
        }
    }
    
    if (ui->btnStop) {
        ui->btnStop->setEnabled(!enabled);
    }
}

void DeviceSearchWidget::addDeviceToTable(const DeviceInfo &device)
{
    qDebug() << "=== DeviceSearchWidget::addDeviceToTable called ===";
    qDebug() << "Table current row count:" << ui->tblDevices->rowCount();
    
    int row = ui->tblDevices->rowCount();
    ui->tblDevices->insertRow(row);
    
    qDebug() << "Inserting device at row:" << row;
    qDebug() << "IP:" << device.ipAddress << "Port:" << device.port;
    
    ui->tblDevices->setItem(row, 0, new QTableWidgetItem(device.ipAddress));
    ui->tblDevices->setItem(row, 1, new QTableWidgetItem(QString::number(device.port)));
    ui->tblDevices->setItem(row, 2, new QTableWidgetItem(device.deviceType));
    ui->tblDevices->setItem(row, 3, new QTableWidgetItem(device.manufacturer));
    ui->tblDevices->setItem(row, 4, new QTableWidgetItem(device.model));
    ui->tblDevices->setItem(row, 5, new QTableWidgetItem(device.status));
    
    qDebug() << "Device added to table. New row count:" << ui->tblDevices->rowCount();
}

void DeviceSearchWidget::updateDeviceDetails(const DeviceInfo &device)
{
    QString details = formatDeviceDetails(device);
    ui->txtDeviceDetails->setHtml(details);
}

void DeviceSearchWidget::updateDeviceCount()
{
    ui->lblDeviceCount->setText(QString("Found %1 devices").arg(m_foundDevices.size()));
}

QString DeviceSearchWidget::formatDeviceDetails(const DeviceInfo &device)
{
    QString html = "<html><body>";
    html += "<h3>Device Information</h3>";
    html += "<table border='1' cellspacing='0' cellpadding='4'>";
    html += QString("<tr><td><b>IP Address:</b></td><td>%1</td></tr>").arg(device.ipAddress);
    html += QString("<tr><td><b>Port:</b></td><td>%1</td></tr>").arg(device.port);
    html += QString("<tr><td><b>Device Type:</b></td><td>%1</td></tr>").arg(device.deviceType);
    html += QString("<tr><td><b>Manufacturer:</b></td><td>%1</td></tr>").arg(device.manufacturer);
    html += QString("<tr><td><b>Model:</b></td><td>%1</td></tr>").arg(device.model);
    html += QString("<tr><td><b>Status:</b></td><td>%1</td></tr>").arg(device.status);
    
    if (!device.webInterface.isEmpty()) {
        html += QString("<tr><td><b>Web Interface:</b></td><td><a href='%1'>%1</a></td></tr>").arg(device.webInterface);
    }
    
    // 显示多种RTSP URL选项
    html += "<tr><td colspan='2'><h4>RTSP Streaming URLs</h4></td></tr>";
    
    // 通道1的主码流和子码流
    html += QString("<tr><td><b>Channel 1 - Main Stream:</b></td><td><span style='font-family:monospace;'>%1</span></td></tr>")
            .arg(device.getMainStreamUrl(1));
    html += QString("<tr><td><b>Channel 1 - Sub Stream:</b></td><td><span style='font-family:monospace;'>%1</span></td></tr>")
            .arg(device.getSubStreamUrl(1));
    
    html += "</table>";
    
    // 添加说明信息
    html += "<p><b>说明：</b></p>";
    html += "<ul>";
    html += "<li><b>主码流 (0)：</b>高分辨率，适合录像和高质量播放</li>";
    html += "<li><b>子码流 (1)：</b>低分辨率，适合预览和移动设备</li>";
    html += "<li><b>通道号：</b>根据设备实际支持的通道数选择使用</li>";
    html += "</ul>";
    
    html += "</body></html>";
    
    return html;
}

// 生成密码凭证（SHA256(password + challenge)）
QString DeviceSearchWidget::generateCredential(const QString &password, const QString &challenge)
{
    QByteArray combinedData = password.toUtf8() + challenge.toUtf8();
    QByteArray hash = QCryptographicHash::hash(combinedData, QCryptographicHash::Sha256);
    return hash.toHex();
}

// 连接到设备并进行登录
void DeviceSearchWidget::connectToDeviceWithLogin(const DeviceInfo &device)
{
    // 显示登录对话框
    QString deviceAddress = QString("%1:%2").arg(device.ipAddress).arg(device.port);
    LoginDialog loginDialog(deviceAddress, this);
    
    if (loginDialog.exec() == QDialog::Accepted) {
        m_currentUsername = loginDialog.getUsername();
        m_currentPassword = loginDialog.getPassword();
        m_rememberMe = loginDialog.getRememberMe();
        m_connectingDevice = device;
        
        if (m_currentUsername.isEmpty()) {
            QMessageBox::warning(this, "警告", "用户名不能为空");
            return;
        }
        
        if (m_currentPassword.isEmpty()) {
            QMessageBox::warning(this, "警告", "密码不能为空");
            return;
        }
        
        // 确保设备已添加到设备管理器中
        if (!m_deviceManager->hasDevice(device.ipAddress)) {
            m_deviceManager->addDevice(device.ipAddress, m_deviceId);
        }
        
        // 连接到设备
        qDebug() << "正在连接到设备:" << device.ipAddress;
        ui->lblProgress->setText(QString("正在连接到 %1:80...").arg(device.ipAddress));
        m_deviceManager->connectToDevice(device.ipAddress);
    }
}

// 设备连接状态变化
void DeviceSearchWidget::onDeviceConnectionStateChanged(const QString &ipAddress, bool connected)
{
    // 只处理当前连接的设备
    if (ipAddress != m_connectingDevice.ipAddress) {
        return;
    }
    
    if (connected) {
        ui->lblProgress->setText("WebSocket连接成功，正在获取挑战码...");
        
        // 更新连接按钮状态
        ui->btnConnect->setText("断开连接");
        ui->btnConnect->setStyleSheet("QPushButton { background-color: red; color: white; }");
        
        // 连接成功后，请求挑战码进行登录
        m_deviceManager->requestChallenge(ipAddress, m_currentUsername);
    } else {
        ui->lblProgress->setText("WebSocket连接已断开");
        
        // 更新连接按钮状态
        ui->btnConnect->setText("连接设备");
        ui->btnConnect->setStyleSheet("");
    }
}

// 设备错误处理
void DeviceSearchWidget::onDeviceError(const QString &ipAddress, const QString &errorMessage)
{
    // 只处理当前连接的设备
    if (ipAddress != m_connectingDevice.ipAddress) {
        return;
    }
    
    QMessageBox::critical(this, "连接错误", QString("WebSocket错误: %1").arg(errorMessage));
    ui->lblProgress->setText(QString("连接错误: %1").arg(errorMessage));
}

// 收到挑战码
void DeviceSearchWidget::onChallengeReceived(const QString &ipAddress, const QString &challenge, int expiresIn)
{
    // 只处理当前连接的设备
    if (ipAddress != m_connectingDevice.ipAddress) {
        return;
    }
    
    ui->lblProgress->setText("收到挑战码，正在进行身份验证...");
    
    // 生成凭证
    QString credential = generateCredential(m_currentPassword, challenge);
    
    // 发送登录请求
    m_deviceManager->login(ipAddress, m_currentUsername, challenge, credential, m_rememberMe);
    
    // 清除密码（安全考虑）
    if (!m_rememberMe) {
        m_currentPassword.clear();
    }
}

// 登录成功
void DeviceSearchWidget::onLoginSuccess(const QString &ipAddress, const QString &accessToken, const QString &refreshToken, const QJsonObject &userInfo)
{
    // 只处理当前连接的设备
    if (ipAddress != m_connectingDevice.ipAddress) {
        return;
    }
    
    // 获取用户名
    QString username = userInfo.contains("username") ? 
                        userInfo["username"].toString() : 
                        m_currentUsername;
    
    ui->lblProgress->setText(QString("登录成功！用户: %1 已连接到设备 %2:%3")
                            .arg(username)
                            .arg(m_connectingDevice.ipAddress)
                            .arg(m_connectingDevice.port));
    
    QMessageBox::information(this, "登录成功", 
                            QString("成功登录到设备 %1:%2\n用户: %3")
                            .arg(m_connectingDevice.ipAddress)
                            .arg(m_connectingDevice.port)
                            .arg(username));
}

// 登录失败
void DeviceSearchWidget::onLoginFailed(const QString &ipAddress, int errorCode, const QString &errorMessage)
{
    // 只处理当前连接的设备
    if (ipAddress != m_connectingDevice.ipAddress) {
        return;
    }
    
    ui->lblProgress->setText(QString("登录失败: %1").arg(errorMessage));
    
    QMessageBox::warning(this, "登录失败", 
                        QString("登录到设备 %1:%2 失败\n错误码: %3\n错误信息: %4")
                        .arg(m_connectingDevice.ipAddress)
                        .arg(m_connectingDevice.port)
                        .arg(errorCode)
                        .arg(errorMessage));
    
    // 登录失败，断开连接
    m_deviceManager->disconnectFromDevice(ipAddress);
}

// 网络配置相关槽函数实现
void DeviceSearchWidget::onNetworkConfigReceived(const QString &ipAddress, const QJsonObject &config)
{
    // 只处理当前连接的设备
    if (ipAddress != m_connectingDevice.ipAddress) {
        return;
    }
    
    ui->lblProgress->setText("网络配置获取成功");
    
    if (m_networkConfigDialog) {
        m_networkConfigDialog->setNetworkConfig(config);
    }
}

void DeviceSearchWidget::onNetworkConfigSetResult(const QString &ipAddress, bool success, const QString &message)
{
    // 只处理当前连接的设备
    if (ipAddress != m_connectingDevice.ipAddress) {
        return;
    }
    
    if (success) {
        ui->lblProgress->setText("网络配置设置成功");
        QMessageBox::information(this, "成功", message);
    } else {
        ui->lblProgress->setText("网络配置设置失败");
        QMessageBox::warning(this, "错误", message);
    }
}

// 网络接口管理实现
void DeviceSearchWidget::loadNetworkInterfaces()
{
    ui->cmbNetworkInterface->clear();
    bool added = false;
    int bestIndex = -1;
    int bestPriority = 9999;
    
    // 获取系统中所有的网络接口
    QList<QNetworkInterface> interfaces = QNetworkInterface::allInterfaces();
    
    for (const QNetworkInterface &interface : interfaces) {
        // 只显示活动的、非回环的接口
        if (!(interface.flags() & QNetworkInterface::IsUp) || 
            (interface.flags() & QNetworkInterface::IsLoopBack)) {
            continue;
        }
        
        // 获取接口的所有IP地址
        QList<QNetworkAddressEntry> entries = interface.addressEntries();
        for (const QNetworkAddressEntry &entry : entries) {
            QHostAddress addr = entry.ip();
            
            // 只处理IPv4地址
            if (addr.protocol() == QAbstractSocket::IPv4Protocol) {
                QString displayName = QString("%1 (%2)").arg(interface.humanReadableName()).arg(addr.toString());
                QString ipAddress = addr.toString();
                
                // 计算优先级：有线(0) < 无线(1) < 其它(2) < 虚拟(3)
                QString hrn = interface.humanReadableName().toLower();
                QString sys = interface.name().toLower();
                bool likelyVirtual = hrn.contains("virtual") || hrn.contains("vmware") || hrn.contains("hyper-v") || hrn.contains("virtualbox") || hrn.contains("tap") || sys.startsWith("vmnet") || sys.startsWith("vbox") || sys.startsWith("tap") || sys.startsWith("ham");
                bool likelyWifi = hrn.contains("wi-fi") || hrn.contains("wifi") || hrn.contains("wlan") || sys.startsWith("wlan") || sys.startsWith("wl");
                bool likelyEth = hrn.contains("ethernet") || hrn.contains("以太") || sys.startsWith("eth") || sys.startsWith("en");
                int priority = 2;
                if (likelyVirtual) priority = 3;
                else if (likelyEth) priority = 0;
                else if (likelyWifi) priority = 1;

                ui->cmbNetworkInterface->addItem(displayName, ipAddress);
                int idx = ui->cmbNetworkInterface->count() - 1;
                added = true;

                if (priority < bestPriority) {
                    bestPriority = priority;
                    bestIndex = idx;
                }
                
                qDebug() << "Found network interface:" << interface.name() 
                         << "(" << interface.humanReadableName() << ")"
                         << "IP:" << ipAddress
                         << "Flags:" << interface.flags()
                         << "Priority:" << priority;
            }
        }
    }
    
    if (added) {
        ui->cmbNetworkInterface->setCurrentIndex(bestIndex >= 0 ? bestIndex : 0);
        if (ui->btnSearch) ui->btnSearch->setEnabled(true);
    } else {
        qWarning() << "No active network interfaces found!";
        ui->cmbNetworkInterface->addItem("No active interfaces found", "");
        if (ui->btnSearch) ui->btnSearch->setEnabled(false);
    }
}

QString DeviceSearchWidget::getSelectedNetworkInterface() const
{
    // 返回选中接口的IP地址，如果是"所有接口"则返回空字符串
    return ui->cmbNetworkInterface->currentData().toString();
}